<?php
/*
 * program:	均源
 * author:	雨中漫步 & 上善若水 & qhxin
 * email:	qhxin@qhxin.com
 * date:	2014/11/11
 * description:	又是一年双十一，不能剁手，就写点东西吧~~~~~~
 */

defined('IN_SCHOOL') or die();

/*{TranslateTagBegin}*/
class base_control{

	private $_site_staus;
	private $_site_title;
	private $_site_keywords;
	private $_site_description;
	private $_site_generator;
	private $_site_author;
	private $_site_copyright;
	private $obj_tmp_stacks = array();
	
	public $confs = array();
	public $this_user;
	public $this_clear;
	public $this_logined = false;
	
	function __construct() {
		$this->init_site_conf();
		$this->init_misc_conf();
		
		$this->check_user_login();
		$this->check_user_lock();
		$this->check_site_lock();

		$this->this_clear = false;
	}
	
	function __destruct() {
	//控制器中须保证此函数最后析构
		$this->make_ctr_do_cache();
		
		$this->debug_refresh_plugin();
		
		defined('APP_OUT_JSON') or $this->debug_out_str();
		
		$this->jy_ob_rewrite();
	}
	
	public function __get($var) {
		if(isset($this->obj_tmp_stacks["$var"]))
						return $this->obj_tmp_stacks["$var"];
		switch($var){
		case 'db':
			global $DB;
			$this->obj_tmp_stacks['db'] = &$DB;
			break;
		case 'cache':
			global $CACHE;
			$this->obj_tmp_stacks['cache'] = &$CACHE;
			break;
		case 'tpl':
			$ext = new Extend('XTpl',
						array(CONFIG_TPL_PATH,CONFIG_TPL_CATH,true,true) );
			$this->obj_tmp_stacks['tpl'] = &$ext->t;
			break;
		case 'upfile':
			$ext = new Extend('UpFile',
						array(CONFIG_UPS_PATH,$this->confs['_file_allow_size'],
									$this->confs['_file_file_ext']) );
			$this->obj_tmp_stacks['upfile'] = &$ext->t;
			break;
		case 'upimg':
			$ext = new Extend('UpFile',
						array(CONFIG_UPS_PATH,$this->confs['_file_allow_size'],
									$this->confs['_file_imgs_ext']) );
			$this->obj_tmp_stacks['upimg'] = &$ext->t;
			break;
		case 'rzimg':
			$ext = new Extend('ResizeImage',array() );
			$this->obj_tmp_stacks['rzimg'] = &$ext->t;
			break;
		case 'wx':
			$ext = new Extend('Wechat');
			$this->obj_tmp_stacks['wx'] = &$ext->t;
			break;
		default:
			if(strlen($var) > 7 && 'EXTEND_' == substr($var, 0,7)) {
				$ext = new Extend($var);
				$this->obj_tmp_stacks["$var"] = &$ext->t;
			}else{
				$varname = 'model_'.$var;
				if(!class_exists($varname, false)) {
					$varfile = CONFIG_MOD_PATH .$varname. '.php';
					if( !file_exists( $varfile )) {
						//插件mod
						foreach(core::$installed_plugin_conf['models'] as $rand=>$arr) {
							if(in_array($varname,$arr)){
								$id = core::$installed_plugin_conf['baseinfo'][$rand]['id'];
								$varfile = CONFIG_PLG_PATH.$id."/$varname.php";
								break;
							}
						}
						clearstatcache();
						if(!file_exists($varfile)) {
							throw new Exception($varfile.' does not exists.');
						}
					}
					$mod_tmp_path = CONFIG_TMP_PATH.'tmp.mod.'. md5($varname.CONFIG_CS_KEY) .'.php';
					$new_inc_mod_file = file_exists($mod_tmp_path)? false : true;
					if(DEBUG || $new_inc_mod_file) {
						$mod_str = file_get_contents($varfile);
						$tmp_str = $otmp_str = Tran::translate($varfile);
						misc::in_key_str($varfile, CONFIG_PLG_PATH) && core::plugin_payed_relic($tmp_str, $varfile); 
						$mod_str = str_replace($otmp_str,$tmp_str,$mod_str);
						//处理hook
						misc::in_key_str($varfile, CONFIG_MOD_PATH) && core::hooks_match_process($mod_str);
						file_put_contents($mod_tmp_path, "$mod_str",LOCK_EX);
					}
					require $mod_tmp_path;
					if(!class_exists($varname, false))
						throw new Exception($varname.' does not exists.');
					$_SERVER['jy_inc_mod'][] = $varname;
				}
				$this->obj_tmp_stacks["$var"] = new $varname;
			}
			break;
		}
		return $this->obj_tmp_stacks["$var"];
	}
	
	public function __call($method, $args) {
		throw new Exception('base_control: Not implement method：'.
								$method.': ('.var_export($args, 1).
							')');
	}
	
	public function message($msg = '', $goto = '', $refresh = TRUE)
	{
		$this->tpl->assign('_message', $msg);
		$this->tpl->assign('_refresh', $refresh);
		if($goto != '') {
			$this->tpl->assign('goto_url', $goto);
		}
		$this->tpl->display('message.tpl');
		exit;
	}
	
	
	public function check_user_login_msg() {
		if(!$this->this_logined)
			$this->message('请先登录账号','index.php?user-login.htm');
	}
	
	//======================>private
	private function init_site_conf() {
		//page header && footer
		$conf = $this->conf->get_site_conf_arr();
		$this->tpl->assign('_site_title', $conf['_site_title']);
		$this->tpl->assign('_site_keywords', $conf['_site_keywords']);
		$this->tpl->assign('_site_description', $conf['_site_description']);
		$this->tpl->assign('_site_generator', $conf['_site_generator']);
		$this->tpl->assign('_site_author', $conf['_site_author']);
		$this->tpl->assign('_site_copyright', $conf['_site_copyright']);
	}
	
	private function init_misc_conf() {
		//merge
		$conf1 = $this->conf->get_file_conf_arr();
		$conf2 = $this->conf->get_misc_conf_arr();
		
		$this->confs = array_merge($conf1, $conf2);
	}
	
	private function check_site_lock() {
		if('user' == core::gpc(0) && 'login' == core::gpc(1) ) return;
		if($this->confs['_conf_viewlock'] == 1 && $this->user->user_groupid() != 100) 
			$this->message('站点暂时关闭访问，抱歉^_^', 'index.php?user-login.htm');
	}
	
	private function check_user_lock() {
		if($this->this_logined && $this->this_user->is_locked())
			$this->message('您的账号已被封锁，禁止访问本站');
	}
	
	private function user_info_assign() {
		$user_core = $this->user->user_core();
		$user_base = $this->user->base_info();
		$user_base = $this->user->user_format($user_base);
		
		$_user_group = $this->user->return_group_name($user_core['groupid']);
		
		$_tj_tjcode = false;
		if('admin' != core::gpc(0)) {
			$_tj_tjcode = true;
		}
		$this->tpl->assign('_tj_tjcode', $_tj_tjcode);
		$this->tpl->assign('_user_group', $_user_group);
		$this->tpl->assign('_user_headphoto', $user_base['headphoto']);
		$this->tpl->assign('_user_laststamp', $user_base['laststamp']);
		$this->tpl->assign('_user_lastip', $user_base['lastip']);
		$this->tpl->assign('_user_email', $this->check_str_empty($user_base['email']));
		$this->tpl->assign('_user_phone', $this->check_str_empty($user_base['phone']));
		$this->tpl->assign('_user_visitc', $user_core['visitc']);
		$this->tpl->assign('_user_core', $user_core['core']);
		$this->tpl->assign('_user_uid', $user_core['uid']);
		$this->tpl->assign('_user_name', $user_core['name']);
		$this->tpl->assign('_user_groupid', $user_core['groupid']);
	}
	
	private function check_str_empty($var) {
		return empty($var)?'暂无':"$var";
	}

	private function check_user_login() {
		$t_sid = core::gpc(CONFIG_COOKIE_PRE .'ssid', 'C');
		$logined = false;
		if(!empty($t_sid) ) {
			$this->this_user = $this->user->get_user_by_ssid($t_sid);
			$logined = $this->this_user->is_logined();
			if($logined) {
				html::setcookie(CONFIG_COOKIE_PRE .'ssid', $t_sid, time()+CONFIG_COOKIE_TIME,'/');
				
				$core_arr = $this->user->user_core();
				//$core_arr['visitc'] += 1;
				$this->user->edit_user($core_arr['uid'], $core_arr['visitc'] ,
							$core_arr['groupid'], '', '', '','',$_SERVER['ip']);
				$this->this_logined = true;
				
				$_user_atmsg_count = $this->atmsg->atmsg_count_unread($core_arr['uid']);
				$this->tpl->assign('_user_atmsg_count', $_user_atmsg_count);
			}
		}
		$this->atmsg->del_old_ten_atmsgs_after_one_mouth();
		$this->kv->del_old_ten_kv_after_one_mouth();
		$this->user_info_assign();
		$this->tpl->assign('_user_islogined', $logined);
	}
	
	private function jy_ob_rewrite() {
		$in_apache = file_exists(IN_APP .'.htaccess');
		$in_other = file_exists(IN_APP .'jyother');
		if($in_apache || $in_other) {
			$content = ob_get_contents();
			$content = str_replace('<a href="index.php?', '<a href="'.$_SERVER['http_protocol'].CONFIG_APP_HOST.'/', $content );
			$content = str_replace('<a href="index.php', '<a href="'.$_SERVER['http_protocol'].CONFIG_APP_HOST.'/', $content );
			$content = str_replace('action="index.php?', 'action="'.$_SERVER['http_protocol'].CONFIG_APP_HOST.'/', $content );
			ob_clean();
			echo $content;
		}else{
			ob_end_flush();
		}
	}
	
	private function debug_refresh_plugin() {
		if(!DEBUG) return;
		
		foreach(core::$installed_plugin_conf['baseinfo'] as $rand=>$arr) {
			$this->plugin->plugin_install($arr['id'], TRUE);
		}
	}
	
	private function debug_out_str() {
		if(!DEBUG) return;
		$out = '';
		$out .= 'ctr_do_md5:<br/>&nbsp;&nbsp;&nbsp;&nbsp;'.$_SERVER['jy_ctr_do'].'<br/>';
		$out .= 'control:<br/>&nbsp;&nbsp;&nbsp;&nbsp;'.$_SERVER['jy_ctr_nm'].'<br/>';
		$out .= 'modles:<br/>';
		foreach( $_SERVER['jy_inc_mod'] as $k=>$v)
			$out .= "&nbsp;&nbsp;&nbsp;&nbsp;$v<br/>";
		$out .= 'extends:<br/>';
		foreach( $_SERVER['jy_inc_ext'] as $k=>$v)
			$out .= "&nbsp;&nbsp;&nbsp;&nbsp;$v<br/>";
	
		$out .= 'memory_usage:<br/>&nbsp;&nbsp;&nbsp;&nbsp;';
		$out .= number_format((memory_get_usage()/1024/1024),3).' MB';
		$out .= '<br/>now_time:<br/>&nbsp;&nbsp;&nbsp;&nbsp;'.date('Y-m-d H:i:s');
		
		echo $out;
	}
	
	private function make_ctr_do_cache() {
		if((DEBUG || !empty($_SERVER['jy_inc_mod']) || !empty($_SERVER['jy_inc_ext']))
				&& !$this->this_clear ) {
			$control_do_tmp_path = CONFIG_TMP_PATH. 'tmp.ctr.'.$_SERVER['jy_ctr_do'] .'.php';
			
			$s = file_get_contents($control_do_tmp_path);
			//ext
			foreach($_SERVER['jy_inc_ext'] as $k=>$ext) {
				$tp = Tran::translate(CONFIG_EXT_PATH . $ext.'.php');
				$s = str_replace('/*{ExtTarget}*/',"$tp/*{ExtTarget}*/",$s);
			}
			//mod
			foreach($_SERVER['jy_inc_mod'] as $k=>$mod) {
				$mod_tmp_path = CONFIG_TMP_PATH. 'tmp.mod.'.md5($mod.CONFIG_CS_KEY) .'.php';
				$tp = Tran::translate($mod_tmp_path);
				$s = str_replace('/*{ModTarget}*/',"$tp/*{ModTarget}*/",$s);
			}
			file_put_contents($control_do_tmp_path, $s,LOCK_EX);
		}
	}
	
}
/*{TranslateTagEnd}*/

?>